﻿using System.Collections.Generic;
using System.Linq;
using Orchard.ContentManagement;
using SchoolPointe.RelatedContent.Drivers;
using SchoolPointe.RelatedContent.Models;
using SchoolPointe.RelatedContent.Services;
using SchoolPointe.Menus.Models;
using Orchard.ContentManagement.Records;

namespace SchoolPointe.Menus.Drivers.RelatedContentDrivers
{
    public class MenuItemChildrenDriver : DefaultRelatedContentDriver
    {
        private readonly IContentManager _contentManager;

        public MenuItemChildrenDriver(IRelatedContentService relatedContentService, IContentManager contentManager) : base(relatedContentService, contentManager)
        {
            _contentManager = contentManager;
        }

        public override string ContentType
        {
            get { return "MenuItem"; }
        }

        public override string RelationshipIdentifier
        {
            get { return "menu-items"; }
        }

        protected override Orchard.ContentManagement.Drivers.DriverResult Editor(RelatedContentRelationship relationship, IEnumerable<ContentItemRecord> relatedItems, IUpdateModel updater, dynamic shapeHelper)
        {                     
            return ContentShape("MenuItemChildren_Editor", () =>
                shapeHelper.MenuItemChildren_Editor(
                    MenuItems: BuildMenuItemEditors(shapeHelper, relatedItems)
                ));
        }

        private List<dynamic> BuildMenuItemEditors(dynamic shapeHelper, IEnumerable<ContentItemRecord> relatedItems)
        {            
            return relatedItems
                .Select(ri => _contentManager.Get<BetterMenuItemPart>(ri.Id))
                .OrderBy(mi => mi.SortOrder)
                .Select(menuItem =>
                {
                    return shapeHelper.NestedEditor(
                        Editor: _contentManager.BuildEditor(menuItem),
                        ParentPrefix: Prefix + "." + menuItem.Id,
                        DisplayType: "Edit");
                })
                .ToList();  
        }
    }
}